﻿using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UITesting;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace TestExtensions
{
    public class UISearch
    {
        public interface IWhereProvider
        {
            UISearch Equals(string propertyValue);
        }

        private class WhereProvider : IWhereProvider
        {
            private UISearch _parent;
            private Action<string> _equalsAction;

            public WhereProvider(UISearch parent, Action<string> equalsAction)
            {
                _parent = parent;
                _equalsAction = equalsAction;
            }

            public UISearch Equals(string propertyValue)
            {
                _equalsAction(propertyValue);
                return _parent;
            }
        }

        #region Variables

        private UITestControl _parentItem;
        private Dictionary<string, string> _searchParameters;

        #endregion

        #region Constructors

        public UISearch(UITestControl parentItem = null)
        {
            _parentItem = parentItem;
            _searchParameters = new Dictionary<string, string>();
        }

        #endregion

        #region Methods

        public IWhereProvider Where(string propertyName)
        {
            return new WhereProvider(this, propertyValue => _searchParameters[propertyName] = propertyValue);
        }

        public TControl Find<TControl>()
            where TControl : UITestControl
        {
            var ctrl = (_parentItem == null)
                ? Activator.CreateInstance<TControl>()
                : Activator.CreateInstance(typeof(TControl), _parentItem) as TControl;
            if (ctrl == null)
            {
                Assert.Fail(string.Format("Cannot create a control of type {0}.", typeof(TControl).Name));
            }

            foreach (var item in _searchParameters)
            {
                ctrl.SearchProperties[item.Key] = item.Value;
            }
            ctrl.Find();
            Assert.IsTrue(ctrl.Exists, "Control could not be found.");

            return ctrl;
        }

        #endregion
    }
}